package com.dgut.lab.security;

import com.dgut.lab.entity.User;
import com.fasterxml.jackson.annotation.JsonInclude;
import lombok.Data;
import lombok.ToString;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

@Data
@ToString
@JsonInclude(JsonInclude.Include.NON_NULL)
public class SecurityUserDetails implements UserDetails {

    private User userInfo;
    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        List<GrantedAuthority> authorities = new ArrayList<>();
//        if(this.getUserInfo()!=null && this.getUserInfo().getRoles()!=null){
//            for (Role role : this.getUserInfo().getRoles()){
//                authorities.add(new SimpleGrantedAuthority("ROLE_"+role.getRoleName()));
//            }
//        }
        if(this.getUserInfo()!=null){
            authorities.add(new SimpleGrantedAuthority("ROLE_"+this.getUserInfo().getRole()));
        }
        else
            authorities.add(new SimpleGrantedAuthority("ROLE_STUDENT"));
        return authorities;
    }

    @Override
    public String getPassword() {
        if(userInfo!=null){
        return this.getUserInfo().getPassword();
        }
        else
            return "";
    }

    @Override
    public String getUsername() {
        return this.getUserInfo().getUsername();

    }


    @Override
    public boolean isAccountNonExpired() {
        return this.getUserInfo().getAccountNonExpired() == null || this.getUserInfo().getAccountNonExpired()==1;
    }

    @Override
    public boolean isAccountNonLocked() {
        return this.getUserInfo().getAccountNonLocked() == null || this.getUserInfo().getAccountNonLocked()==1;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return this.getUserInfo().getCredentialsNonExpired() == null|| this.getUserInfo().getCredentialsNonExpired()==1;
    }

    @Override
    public boolean isEnabled() {
        return this.getUserInfo().getEnabled() == null || this.getUserInfo().getEnabled()==1;
    }
}
